package com.yimi.yinhepda.downLoadBaseData;

import android.app.Dialog;
import android.content.Context;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.pda.ym.base.BaseActivity;
import com.pda.ym.updateApk.UpdateApk;
import com.yimi.yinhepda.R;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.helper.DbHelperUC;
import com.yimi.yinhepda.entity.response.QueryUCDownUrlResponse;
import com.yimi.yinhepda.entity.response.QueryUcRouteDbResponse;
import com.pda.ym.net.NetRequest;
import com.pda.ym.utils.AppInfoHelper;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.FileUtil;
import com.yimi.yinhepda.utils.GzipUtil;
import com.pda.uce.commom.util.LogUtil;
import com.yimi.yinhepda.utils.OkHttpDownUtil;
import com.pda.ym.utils.SharedPreferUtil;
import com.yimi.yinhepda.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * 下载壹米在手文件
 *
 * @author 000432
 * @date 2018/7/4 0004
 */

public class DownLoadFile {

    private Dialog builder = null;
    private TextView tv_content = null;
    private ProgressBar pb = null;
    private static Context mContext;
    public static DownLoadFile INSTANCE;

    public static DownLoadFile getInstance(Context context) {
        if (mContext != null) {
            if (!context.getClass().equals(mContext.getClass())) {
                INSTANCE = null;
            }
        }
        if (INSTANCE == null) {
            synchronized (UpdateApk.class) {
                if (INSTANCE == null) {
                    INSTANCE = new DownLoadFile(context);
                }
            }
        }
        return INSTANCE;
    }

    public DownLoadFile(Context context) {
        mContext = context;
    }

    public void downloadAPP() {
        ((BaseActivity) mContext).showPgDlg("查询数据中...");
        Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<? super Void> subscriber) {
                try {
                    String updateInfo = AppInfoHelper.getServerInfo(Constants.APP_UPDATE_INFO_SERVER_URL);
                    JSONObject object = new JSONObject(updateInfo);
                    JSONObject data = object.getJSONObject("data");
                    Constants.DOWN_LOAD_YIMIDIDA_APP_URL = data.getString("downloadUrl");
                    subscriber.onCompleted();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Void>() {
            @Override
            public void onCompleted() {
                ((BaseActivity) mContext).dismissPgDlg();
                download(Constants.DOWN_LOAD_YIMIDIDA_APP_URL, Constants.STROAGEPATH + Constants.YIMIDIDA_APP_NAME, new UICallBack() {
                    @Override
                    public void onError(String msg) {

                    }

                    @Override
                    public void onSuccess(Object obj) {
                        FileUtil.installAPK(Uri.fromFile(new File(((ResponseInfo<File>) obj).result.getPath())), mContext);
                    }
                });
            }

            @Override
            public void onError(Throwable throwable) {
                ((BaseActivity) mContext).dismissPgDlg();
                ((BaseActivity) mContext).showToast("加载数据失败！");
            }

            @Override
            public void onNext(Void aVoid) {
            }
        });
    }

    /**
     * 下载优速APP
     */
    public void downloadUCAPP() {
        //获取优速app下载地址
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setUrl(Constants.DOWN_LOAD_UC_EXPRESS_APP_URL)
                .setParams(null)
                .setResponsClazz(QueryUCDownUrlResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        ToastUtil.showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        QueryUCDownUrlResponse response = (QueryUCDownUrlResponse) obj;
                        if (response != null && response.getResult() != null) {
                            try {
                                builder = new Dialog(mContext);
                                LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                                View layout = inflater.inflate(R.layout.dialog_download, null);
                                tv_content = layout.findViewById(R.id.tv_content);
                                pb = layout.findViewById(R.id.progressBar);
                                builder.setTitle("程序下载");
                                builder.setContentView(layout);
                                builder.setCancelable(false);
                                builder.setCanceledOnTouchOutside(false);
                                builder.show();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            //获取到优速app下载链接后，开始下载
                            OkHttpDownUtil.get().download(response.getResult(), Constants.STROAGEPATH, Constants.UC_EXPRESS_APP_NAME, new OkHttpDownUtil.OnDownloadListener() {
                                @Override
                                public void onDownloadSuccess() {
                                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                                        @Override
                                        public void run() {
                                            builder.dismiss();
                                            FileUtil.installAPK(Uri.fromFile(new File(Constants.STROAGEPATH + Constants.UC_EXPRESS_APP_NAME)), mContext);
                                        }
                                    });
                                }

                                @Override
                                public void onDownloading(int progress) {
                                    try {
                                        tv_content.setText("程序下载百分比：" + progress + "/100%");
                                        pb.setMax(100);
                                        pb.setProgress(progress);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }

                                @Override
                                public void onDownloadFailed() {
                                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                                        @Override
                                        public void run() {
                                            builder.dismiss();
                                            ToastUtil.showToast("下载失败！");
                                        }
                                    });
                                }
                            });
                        }
                    }
                });
    }

    /**
     * 下载快递路由db文件
     */
    public void downloadUcRouteDbFile(final QueryUcRouteDbResponse.DataBean dataBean) {
        if (dataBean.getUrl() != null) {
            OkHttpDownUtil.get().download(dataBean.getUrl(), DbHelperUC.DB_PATH, DbHelperUC.DB_ZIP_NAME, new OkHttpDownUtil.OnDownloadListener() {
                @Override
                public void onDownloadSuccess() {
                    //解压缩db文件
                    boolean unzipSuccess = GzipUtil.uncompressZip4j(DbHelperUC.DB_PATH + DbHelperUC.DB_ZIP_NAME, DbHelperUC.DB_PATH, DbHelperUC.DB_NAME);
                    if (dataBean.getIncrementTime() != null && unzipSuccess) {
                        SharedPreferUtil.getInstance().setValue(Common.UC_ROUTE_DB_SYNC_TIME, dataBean.getIncrementTime());
                    }
                }

                @Override
                public void onDownloading(int progress) {
                    LogUtil.e("路由db文件下载百分比：" + progress + "/100%");
                }

                @Override
                public void onDownloadFailed() {
                    LogUtil.e("路由db文件下载失败！");
                }
            });
        }
    }

    public void download(String url, String path, final UICallBack uiCallBack) {
        HttpUtils http = new HttpUtils();
        http.download(url, path, false, false,
                new RequestCallBack<File>() {
                    @Override
                    public void onStart() {
                        try {
                            builder = new Dialog(mContext);
                            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                            View layout = inflater.inflate(R.layout.dialog_download, null);
                            tv_content = layout.findViewById(R.id.tv_content);
                            pb = layout.findViewById(R.id.progressBar);
                            builder.setTitle("程序下载");
                            builder.setContentView(layout);
                            builder.setCancelable(false);
                            builder.setCanceledOnTouchOutside(false);
                            builder.show();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        try {
                            tv_content.setText("程序下载百分比：" + current * 100 / total + "%");
                            pb.setMax((int) total);
                            pb.setProgress((int) current);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onSuccess(ResponseInfo<File> responseInfo) {
                        try {
                            builder.dismiss();
                            uiCallBack.onSuccess(responseInfo);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        try {
                            builder.dismiss();
                            LogUtil.e(msg);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
}
